using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class UI : MonoBehaviour {
	
	public GUIText tempText;
	
	static public int currentTuturialSlide; //Currrent tutorial slide
	
	//Background plan object
	static public GameObject bgPlan;
	
	//Level base obejct
	static public GameObject lvBase;
	
	//Touch type
  	public enum touchType {
		NoAction, SingleTap, TapAndHold, SlideLeft, SlideRight, Released
	};
	
	//Current scene
  	public enum CurrentSceneEnum {
		MainMenu, Option, ResetDataConfirm, UpdateConfirm, ExitConfirm, Pause,
		ResetDataOK, About, LevelList, InLevel, LevelComplete
	};

	//UI Element
  	public enum UIElenmentEnum {
		MainMenu, Option, ResetDataConfirm, UpdateConfirm, ExitConfirm, Pause,
		ResetDataOK,About, LevelList, InLevel, LevelComplete
	};
	
	//Current scene
	static public bool isCanTouch = true;
	static public CurrentSceneEnum currentScene;
	private RaycastHit raycastHit;
	public Texture selectedTexture;
	public Texture normalTexture;
	
	//GUI style
	private GUIStyle uiStyle_L1;
	private GUIStyle uiStyle_L2;
	private GUIStyle uiStyle_S;
	public Font gameFont;
	
	//Textures-----------------------------------------------------------------
	
	public Texture fullScreenLayout;
	
	//Touch position data
	private Vector2 touchPos;
	private Vector3 touchDelta;
	
	//Touch status
	private touchType touchStatus;
	private TouchPhase currentTouchPhase;
	
	//Hold time
	private float holdTime;
	
	//Popup 
	static public bool isShowLevelCompleteForm = false;
	static public bool isShowTutorial = false;
	
	//String message
	private string exitConfirmMessage = "Do you really\nwant to exit!?";
	private string updateConfirmMessage = "The lastest version is\navailable, do you want\nto update?";
	private string resetDataConfirmMessage = "Are you sure you\nwant to reset your\nprogress?";
	private string resetDataCompleteMessage = "Your progress has\nbeen reset!";
	
	static private GameObject currentObject;
	static private int currentColor = -1;
	private GameObject hitObject;
	
	private GameCore gameCore;
	
	static public List<GameObject> currentLine;
	static public List<GameObject> currentSelectionLine;
	
	//UI Rects
	private Rect rctFullScreen;
	
	private Rect rctSkill1;
	private Rect rctSkill2;
	private Rect rctSkill3;
	
	private Rect rctScore;
	private Rect rctSkillPoint;
	
	//
	private int unitWidth;
	private int unitHeight;
	
	// Use this for initialization
	void Start () {
		UIInit();
		InitUIStyle();
		RectInit();
	}
	
	void UIInit () {
		
		GameObject gameCoreObject = GameObject.Find("GameCore");
		gameCore = gameCoreObject.GetComponent<GameCore>();
		
		currentLine = new List<GameObject>();
		currentSelectionLine = new List<GameObject>();
	}
	
	void RectInit () {
		rctFullScreen = new Rect(0, 0, Screen.width, Screen.height);
		
		unitWidth = Screen.width / 7;
		unitHeight = Screen.height / 15;
		rctSkill1 = new Rect(unitWidth*4, unitHeight*14, unitWidth, unitHeight*2);
		rctSkill2 = new Rect(unitWidth*5, unitHeight*14, unitWidth, unitHeight*2);
		rctSkill3 = new Rect(unitWidth*6, unitHeight*14, unitWidth, unitHeight*2);
		
		rctScore = new Rect(10,-2,Screen.width, unitHeight);
		rctSkillPoint = new Rect(10,unitHeight*14, unitWidth*3, unitHeight);
		
	}
	
	/// <summary>
	/// Update this instance.
	/// </summary>
	// Update is called once per frame, get input to process
	void Update () {

		//if(Input.touches.Length > 0) {
			
			//Get current touch phase
			//currentTouchPhase = Input.touches[0].phase;
			
			//Sliding...?
			//if(currentTouchPhase != TouchPhase.Ended) {
			if(Input.GetMouseButtonDown(0)) {
				Ray ray = Camera.main.ScreenPointToRay(GetCurrentTouchPos()); //Ray ray = Camera.main.ScreenPointToRay(touchPos);
				if(Physics.Raycast(ray, out raycastHit, 2)) {
					hitObject = raycastHit.transform.gameObject;
					string objTag = hitObject.tag;
			
					//Process
					if(objTag == "EnemyShip") {
					
						Enemy enemy = hitObject.GetComponent<Enemy>();

						//Super boom
						if(GameManager.superBoom == true) {
							gameCore.SuperBoom(hitObject);
							GameManager.superBoom = false;
							return;
						}
					
						//Change enemy's ship color
						if(GameManager.changeEnemyColor == true) {
							
							/*if(enemy.color != GameManager.tempBulletColor) {
								GameManager.tempBulletColor = enemy.color;
							}*/
						
							GameManager.tempBulletColor++;
							if(GameManager.tempBulletColor > 3) {
								GameManager.tempBulletColor = 1;
							}
						
							enemy.color = GameManager.tempBulletColor;
							
							Spriter spriter = hitObject.GetComponent<Spriter>();
							if(GameManager.tempBulletColor == 1) {
								spriter.texturesPack = GameCore.gameManager.enemyTexturePack1;
							}
							else if(GameManager.tempBulletColor == 2) {
								spriter.texturesPack = GameCore.gameManager.enemyTexturePack2;
							}
							else if(GameManager.tempBulletColor == 3) {
								spriter.texturesPack = GameCore.gameManager.enemyTexturePack3;
							}
						
							GameCore.Cell cell = GameCore.GetCellFromObjectName(hitObject.name);
							GameManager.currentLevelGrid[cell.row,cell.col] = (byte)GameManager.tempBulletColor;
							GameManager.playerSkillPoint--;	
						
							if(GameManager.playerSkillPoint < 1) {
								GameManager.changeEnemyColor = false;
							}
						
							return;
						}
					
						//Normal-----------------------------------------------------------------	
					
						if(currentColor == -1) { //First touch?
							currentColor = enemy.color;
						}
	
						if(currentObject != null && hitObject != currentObject) {
							//Is nearest cell?
							if(GameCore.isNearestCell(hitObject.name,currentObject.name) == false) {
								ClearCurrentLine();
								return;
							}
						}
							
						if(enemy.color == currentColor) { //Same color
							if(hitObject != currentObject) {
								currentObject = hitObject;
								currentLine.Add(hitObject);
								//currentObject.renderer.material.mainTexture = GameCore.gameManager.enemyShipTexture[0];
								GameObject selectionMark = Instantiate(GameCore.gameManager.selectionObject) as GameObject;
								currentSelectionLine.Add(selectionMark);
								Vector3 selectedPosition = hitObject.transform.position;
								selectedPosition.z = selectedPosition.z + 0.02f;
								selectionMark.transform.position = selectedPosition;
							}
						}
						else {
							ClearCurrentLine();
						}
						//-----------------------------------------------------------------------
					}
				}
			}
			
			//else if(currentTouchPhase == TouchPhase.Ended && currentLine.Count>0) {
			if(Input.GetKeyDown(KeyCode.A) && currentLine.Count>0) {
				StartCoroutine(gameCore.Shoot(currentLine, GameManager.player));
			}
		//}
		
		//Single tap
		//if(Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began){
		if(Input.GetMouseButtonDown(0)) {
			GetTouchPos();
			touchStatus = touchType.SingleTap;
			
			//Skill: Super boom
			if(rctSkill1.Contains(touchPos)) {
				if(GameManager.playerSkillPoint >= 3) {
					GameManager.superBoom = true;
					GameManager.playerSkillPoint = GameManager.playerSkillPoint - 2;
				}
			}
			
			//Skill: Change bullet color
			if(rctSkill2.Contains(touchPos)) {
				if(GameManager.playerSkillPoint >= 1) {
					//Change bullet color	
					GameManager.tempBulletColor++;
					if(GameManager.tempBulletColor > 3) {
						GameManager.tempBulletColor = 1;
					}
				
					GameManager.currentBulletColor = GameManager.tempBulletColor;
					GameManager.playerSkillPoint--;	
					
					Destroy(GameManager.currentBullet);
					GameCore.gameManager.GenerateBullet();
					
					return;
				}
			}
			
			//Skill: Change enenmy's spaceship color
			if(rctSkill3.Contains(touchPos)) {
				if(GameManager.playerSkillPoint >= 1 && GameManager.changeEnemyColor == false) {
					GameManager.changeEnemyColor = true;
					GameManager.tempBulletColor = GameManager.currentBulletColor;
				}
				else if(GameManager.changeEnemyColor == true) {
					GameManager.changeEnemyColor = false;
				}
			}
	    }
		
		
		//Tap and hold
		if(Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Stationary){
		//if(Input.GetMouseButton(0)) {
			GetTouchPos();
			touchStatus = touchType.TapAndHold;
				
		}
		
		//Slide
		if(Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved) {
			
			GetTouchPos();
			touchDelta = Input.GetTouch(0).deltaPosition;
			
			//Slide left
			if(touchDelta.x < -0.5f) {
				touchStatus = touchType.SlideLeft;
			}
			
			//Slide right
			if(touchDelta.x > 0.5f) {
				touchStatus = touchType.SlideRight;
			}

    	}
		
		//Touch end
		if(Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Ended) {
			
			//End slide left
			if(touchStatus == touchType.SlideLeft) {
				
			}
				
			//End slide right
			if(touchStatus == touchType.SlideRight) {
			
			}
		}
	}
	
	void GetTouchPos () {
		//touchPos = Input.GetTouch(0).position;
		//touchPos.y = Screen.height - touchPos.y;
		
		touchPos = Input.mousePosition;
		touchPos.y = Screen.height - touchPos.y;
	}
	
	Vector3 GetCurrentTouchPos () {
		
		/*Vector3 currentTouchPos = Input.GetTouch(0).position;
		currentTouchPos.y = Screen.height - currentTouchPos.y;*/
		Vector3 currentTouchPos = Input.mousePosition;
		//currentTouchPos.y = Screen.height - currentTouchPos.y;
		
		return currentTouchPos;
	}
	
	/// <summary>
	/// Raises the GU event.
	/// </summary>
	
	//Draw scene texture
	void OnGUI(){
	    //tempText.text = GameManager.playerScore.ToString();
		tempText.text = GameManager.currentBulletColor.ToString();
		GUI.DrawTexture(rctFullScreen, fullScreenLayout);
		GUI.Box(rctSkill1, "");
		GUI.Box(rctSkill2, "");
		GUI.Box(rctSkill3, "");
		GUI.Label(rctScore, "Score: " + GameManager.playerScore, uiStyle_S);
		GUI.Label(rctSkillPoint, "Skill pt: " + GameManager.playerSkillPoint, uiStyle_S);
		
	}	

	private void InitUIStyle () {
		uiStyle_L1 = new GUIStyle();
		uiStyle_L1.font = gameFont;
		uiStyle_L1.fontSize = 35;
		uiStyle_L1.normal.textColor = Color.white;
		uiStyle_L1.alignment = TextAnchor.MiddleCenter;
		
		uiStyle_S = new GUIStyle(uiStyle_L1);
		uiStyle_S.fontSize = 30;
		
		uiStyle_L2 = new GUIStyle(uiStyle_L1);
		uiStyle_L2.normal.textColor = Color.red;
	}
	
	//Clear current line and current selection mark
	static public void ClearCurrentLine () {

		foreach(GameObject mark in currentSelectionLine) {
			Destroy(mark);
		}

		currentLine.Clear();
		currentSelectionLine.Clear();
		currentColor = -1;
		currentObject = null;
	}
	
	private IEnumerator ShowLevelCompletePopup () {
		
		yield return 0;
	}
	
	/*private IEnumerator ScoreCountUp () {
		for(tmpScore=0; tmpScore<=GameManager.levelScore; tmpScore++) {
			yield return new WaitForSeconds(0.025f);
			tmpScore = tmpScore + 100;
		}
	}*/
	
	//Transition effect - use for start/end level
	static public void TransitionEffect (bool isOpen) {

	}
	
	//Lerpcolor - use for plash screen effect
	static public IEnumerator LerpColor (Color cFrom, Color cTo) {

		Color lerpedColor = cFrom;
		float delta = 0.05f;

		while(lerpedColor != cTo) {
			delta = delta + 0.05f;
			lerpedColor = Color.Lerp(cFrom, cTo, delta);
			RenderSettings.ambientLight = lerpedColor;
			
			yield return new WaitForSeconds(0.025f);	
		}
	}
	
	
	//Get mini rect for scaling effect
	private Rect GetMinimumRect (Rect srcRect) {
		Rect result = new Rect(0,0,0,0);
		
		result.x = srcRect.x + srcRect.width/2;
		result.y = srcRect.y + srcRect.width/2;
		return result;
	}
	
	//Get mini rect for scaling effect
	private Rect GetSmallRect (Rect srcRect) {
		Rect result = new Rect(0,0,0,0);
		
		result.x = srcRect.x + 20;
		result.y = srcRect.y + 20;
		result.width = srcRect.width - 40;
		result.height = srcRect.height - 40;
		return result;
	}
	
	//Get mini rect for scaling effect
	private Rect GetLargeRect (Rect srcRect) {
		Rect result = new Rect(0,0,0,0);
		
		result.x = srcRect.x - 30;
		result.y = srcRect.y - 30;
		result.width = srcRect.width + 60;
		result.height = srcRect.height + 60;
		return result;
	}
	
	//UI scaling effect
	public IEnumerator UIEffect (UIElenmentEnum uiElement) {
		
		/*currentUIElement = uiElement;
		
    	rctTempUI = new Rect(0,0,0,0);
		
		switch(uiElement) {
		case UIElenmentEnum.MainMenu:
		case UIElenmentEnum.Option:
		case UIElenmentEnum.LevelList:
		case UIElenmentEnum.LevelComplete:
		case UIElenmentEnum.ResetDataConfirm:
		case UIElenmentEnum.ResetDataOK:
		case UIElenmentEnum.Pause:
		case UIElenmentEnum.ExitConfirm:
		case UIElenmentEnum.UpdateConfirm:
			rctTempUI = rctOverlayScreen;
			
        	EKTween.ValueTo(gameObject, EKTween.EKDict("from", GetMinimumRect(rctTempUI), "to", GetLargeRect(rctTempUI), "time", 0.2f, "onupdate", "UpdateUIRect", "oncomplete", "EnableTouch"));
			yield return new WaitForSeconds(0.2f);
			
			EKTween.ValueTo(gameObject, EKTween.EKDict("from", GetLargeRect(rctTempUI), "to", GetSmallRect(rctTempUI), "time", 0.065f, "easetype", EKTween.EaseType.EaseOutQuard, "onupdate", "UpdateUIRect", "oncomplete", "EnableTouch"));
			yield return new WaitForSeconds(0.08f);
			
			EKTween.ValueTo(gameObject, EKTween.EKDict("from", GetSmallRect(rctTempUI), "to", rctTempUI, "time", 0.065f, "easetype", EKTween.EaseType.EaseOutQuard, "onupdate", "UpdateUIRect", "oncomplete", "EnableTouch"));
			yield return new WaitForSeconds(0.08f);
			
			break;
		}
		 */
		
		yield return 0;
	}
	
	//Update rect
	private void UpdateUIRect (Rect newRect) {
		
		/*switch(currentUIElement) {
		case UIElenmentEnum.MainMenu:
		case UIElenmentEnum.Option:
		case UIElenmentEnum.LevelList:
		case UIElenmentEnum.LevelComplete:
		case UIElenmentEnum.ResetDataConfirm:
		case UIElenmentEnum.ResetDataOK:
		case UIElenmentEnum.Pause:
		case UIElenmentEnum.ExitConfirm:
		case UIElenmentEnum.UpdateConfirm:
			rctOverlayScreen = newRect;
			break;
		}*/		

	}
	
	private IEnumerator EnableTouch () {
		
		yield return new WaitForSeconds(0.5f);
		isCanTouch = true;	
	}
}
